<template>
    <div class="sms-container">
        <el-form ref="smsLoginForm" :model="smsFormData" status-icon :rules="smsRules" label-width="120px"
                 class="demo-smsFormData">
            <!-- 输入手机号 -->
            <el-form-item label="手机号" prop="phone" class="captcha">
                <el-input v-model="smsFormData.phone" maxlength="11" />
                <span @click="sendSms">{{ desc }}</span>
            </el-form-item>

            <!-- 输入验证码 -->
            <el-form-item label="验证码" prop="code">
                <el-input v-model="smsFormData.code" maxlength="5" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(smsLoginForm)">登入</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>


//业务:

//1.修改表单注入的数据以及prop

//2.给smsLogin这个组件添加自己的表单form校验规则

import { reactive, ref, onUnmounted } from 'vue'
import { ElLoading, ElMessage } from "element-plus"
import { useRouter } from "vue-router"
import useUsers from "@/store/users"

//引入发送请求的api

import * as api from "@/api/users"

//创建form组件的引用

const smsLoginForm = ref()

//表单验证函数

const validatePhone = (rule, value, callback) => {
    //手机号正则
    let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
    if (reg.test(value)) {
        callback()
    } else {
        callback(new Error('手机号格式不正确'))
    }
}

//校验手机验证码
const validateCode = (rule, value, callback) => {
    if (value.length < 5) {
        callback(new Error('验证码最少5位'))
    } else {
        callback()
    }
}


//表单规则

const smsRules = reactive({
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    code: [{ validator: validateCode, trigger: 'blur' }],
})

let router = useRouter()
//使用submitForm
let submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async valid => {
        if (valid) {
            //表单校验通过
            //打开全屏的loading
            const loading = ElLoading.service({
                lock: true,
                text: '正在登入...',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            try {
                //请求登入
                let res = await api.smsLoginApi(smsFormData.code);
                console.log(res)
                //登入成功
                //1.存储token到sessionStorage (token是令牌,是客户端和后端通信的一个凭据,如果不传,后台就不返回信息)
                sessionStorage.setItem('gqq', res.data.token)
                //2.存储用户信息到pinia
                let usersStore = useUsers();
                usersStore.setUserInfo(res.data.userInfo)
                usersStore.permission = res.data.permission.buttons;
                // console.log(router)
                //3.跳转到首页
                router.push('/')
                //4.关闭全屏的loading动画
                loading.close()
            } catch (e) {

            }

        }
    })
}

//注入到表单的数据
const smsFormData = reactive({
    phone: "",
    code: ''
})

//短信登入流程

//1.输入手机号,点击发送按钮,获取短信验证码

//短信验证码需要进行倒计时提示

//手机验证码同一个手机,一分钟只能发送一次,一天一个手机号只能发6次

//2.输入短信验证码,进行登入请求




//引用定时器,便于组件卸载的时候,清除定时器
let timeDownInterval = null;
//处理用户频繁点击的问题
//应用开关的思路
//初始值用户未点击
let isClick = false;
//声明响应式变量,用于展示按钮正在倒计时的文字


let desc = ref('点击发送')

let sendSms = async () => {
    // console.log(smsLoginForm)
    try {
        if (!isClick) {
            //调用接口,获取手机验证码
            await api.getSmsCodeApi(smsFormData.phone);
            //提示短信发送成功
            ElMessage.success('短信发送成功,请查看手机短信')
            //开关关闭的情况下
            //变更开关的状态是打开
            isClick = true;
            //开始倒计时
            timeDownInterval = timeDown(25, desc, '秒后发送', '点击发送', () => {
                console.log('倒计时结束')
                //把开关重置为关闭状态
                isClick = false
            })
        }
    } catch (e) {
        console.log(e)
    }
}


//短信倒计时的方法
/**
 * @param {Number} timer 倒计时的时间
 * @param {Object} param 需要变更的响应式变量
 * @param {String} msg 倒计时秒数的文字 
 * @param {String} endMsg 倒计时结束之后,回显的文字
 * @param {Function} cb 倒计时结束之后回调的函数
 */

//封装的思路,目的就是为了让使用能够变简单,复杂的逻辑放在函数内部

//字符串.padStart('希望几位数','用什么字符去补')

let timeDown = (timer = 5, param, msg, endMsg, cb) => {
    //实现思路,核心就是间隔定时器
    let count = timer;
    //一调用倒计时函数,就要显示倒计时的秒数
    param.value = (count + "").padStart(2, 0) + msg;
    let interval = setInterval(() => {
        count--
        // console.log(9999)
        if (count <= 0) {
            //清除定时器
            clearInterval(interval)
            //倒计时结束
            param.value = endMsg
            //回调传入的函数
            cb && cb()
            return
        }
        param.value = (count + "").padStart(2, 0) + msg
    }, 1000)
    //返回定时器的引用
    return interval
}

//在组件卸载的时候,清除定时器
onUnmounted(() => {
    clearInterval(timeDownInterval)
})

</script>



<style scoped lang="scss">
.captcha {
    display: flex;

    :deep(.el-input) {
        width: 170px;
        border-right: none;

        .el-input__wrapper {
            border-radius: 5px 0 0 5px;
            box-shadow: none;
        }
    }

    span {
        height: 42px;
        background-color: #fff;
        display: inline-block;
        border-left: none;
        border-radius: 0 5px 5px 0;
        width: 32%;
        color: #666;
        font-size: 14px;
        font-weight: 900;
        line-height: 42px;
        cursor: pointer;
        text-decoration: underline;
    }
}

.el-form {
    padding-right: 50px;
    margin-left: -20px;

    :deep(.el-button--primary) {
        height: 40px;
        width: 250px;
        background: linear-gradient(90deg, #1596fb, #002dff)
    }
}

:deep(.el-form-item__label) {
    color: #fff;
    line-height: 40px
}

:deep(.el-input__inner) {
    height: 40px;
}
</style>